//
//  DR_FavoriteVC.swift
//  DocReaderRP
//
//  Created by  mac on 2025/11/19.
//

import UIKit
import SnapKit
import Toast_Swift

class DR_FavoriteVC: DR_BaseVC {
    
    private let filesCollectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 16
        layout.minimumInteritemSpacing = 12
        layout.sectionInset = UIEdgeInsets(top: 0, left: 15, bottom: 15, right: 15)
        
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = .white
        cv.showsVerticalScrollIndicator = false
        cv.register(DR_HomeFileCell.self, forCellWithReuseIdentifier: DR_HomeFileCell.identifier)
        return cv
    }()
    
    private var favoriteFiles: [DR_FileModel] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        setupConstraints()
        loadFavoriteFiles()
        
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
        
        // 监听文件导入和收藏变化通知
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(handleFileImported),
            name: NSNotification.Name("FileImported"),
            object: nil
        )
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 每次显示时刷新收藏文件列表
        loadFavoriteFiles()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc private func handleFileImported() {
        // 刷新文件列表
        loadFavoriteFiles()
    }
    
    private func setupUI(){
        view.addSubview(backButton)
        view.addSubview(titleLabel)
        view.addSubview(filesCollectionView)
        
        // 设置 collection view
        filesCollectionView.delegate = self
        filesCollectionView.dataSource = self
    }
    
    private func setupConstraints(){
        backButton.snp.makeConstraints { make in
            make.leading.equalToSuperview()
            make.top.equalTo(view.safeAreaLayoutGuide)
            make.width.equalTo(56)
            make.height.equalTo(44)
        }
        titleLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(backButton)
        }
        
        filesCollectionView.snp.makeConstraints { make in
            make.leading.trailing.bottom.equalToSuperview()
            make.top.equalTo(backButton.snp.bottom).offset(10)
        }
    }
    
    // MARK: - 加载收藏文件列表
    private func loadFavoriteFiles() {
        favoriteFiles = DR_FileManager.shared.getFavoriteFiles()
        filesCollectionView.reloadData()
    }
    
    // MARK: - 显示更多选项弹窗
    private func showMoreActionSheet(for fileModel: DR_FileModel) {
        let actionSheet = DR_FileMoreActionSheet()
        
        // 根据文件类型决定显示哪些操作
        var actions: [DR_FileMoreAction] = []
        
        // PDF 特有操作
        if fileModel.fileType == .pdf {
            actions.append(DR_FileMoreAction(title: "home_merge".localized, iconName: "more_merge", action: { [weak self] in
                self?.handleMergePDF()
            }))
            actions.append(DR_FileMoreAction(title: "home_split".localized, iconName: "more_split", action: { [weak self] in
                self?.handleSplitPDF(fileModel)
            }))
            
            // 根据是否已设置密码显示不同的操作
            let lockTitle = DR_PDFTool.shared.hasPassword(for: fileModel.fileURL) ? "Unlock PDF" : "home_lock".localized
            actions.append(DR_FileMoreAction(title: lockTitle, iconName: "more_lock", action: { [weak self] in
                self?.handleLockPDF(fileModel)
            }))
        }
        
        // 通用操作
        let isFavorite = DR_FileManager.shared.isFavorite(fileModel)
        let favoriteTitle = isFavorite ? "more_collected".localized : "more_collection".localized
        let favoriteIcon = isFavorite ? "home_collected" : "home_collect"
        actions.append(DR_FileMoreAction(title: favoriteTitle, iconName: favoriteIcon, action: { [weak self] in
            self?.handleToggleFavorite(fileModel)
        }))
        
        actions.append(DR_FileMoreAction(title: "more_share".localized, iconName: "more_share", action: { [weak self] in
            self?.handleShareFile(fileModel)
        }))
        actions.append(DR_FileMoreAction(title: "more_rename".localized, iconName: "more_rename", action: { [weak self] in
            self?.handleRenameFile(fileModel)
        }))
        actions.append(DR_FileMoreAction(title: "more_detail".localized, iconName: "more_detail", action: { [weak self] in
            self?.handleShowDetails(fileModel)
        }))
        actions.append(DR_FileMoreAction(title: "more_del".localized, iconName: "more_del", action: { [weak self] in
            self?.handleDeleteFile(fileModel)
        }))
        
        actionSheet.configure(with: DR_SearchFileModel(from: fileModel), actions: actions)
        
        // 确保显示在 window 或 tabBarController 的 view 上
        if let window = UIApplication.shared.keyWindowCompat {
            actionSheet.show(in: window)
        } else if let tabBarController = self.tabBarController {
            actionSheet.show(in: tabBarController.view)
        } else {
            actionSheet.show(in: view)
        }
    }
    
    // MARK: - 处理Merge PDF
    private func handleMergePDF() {
        let selVC = DR_SelectVC()
        selVC.type = 1
        pushHidingTabBar(selVC, animated: true)
    }
    
    // MARK: - 处理Split PDF
    private func handleSplitPDF(_ fileModel: DR_FileModel) {
        // 检查PDF是否被锁定
        if DR_PDFTool.shared.hasPassword(for: fileModel.fileURL) {
            // PDF已锁定，需要先输入密码
            let passwordSheet = DR_EnterPasswordSheet()
            passwordSheet.configure(fileName: fileModel.fileName, fileSize: fileModel.fileSizeString)
            
            passwordSheet.onConfirm = { [weak self, weak passwordSheet] password in
                guard let self = self, let sheet = passwordSheet else { return }
                if DR_PDFTool.shared.verifyPassword(for: fileModel.fileURL, password: password) {
                    sheet.hide()
                    self.openSplitPDFVC(fileModel: fileModel)
                } else {
                    self.view.makeToast("密码错误", duration: 2.0, position: .center)
                }
            }
            
            passwordSheet.onCancel = {
                // 取消操作，不需要处理
            }
            
            // 确保显示在 window 或 tabBarController 的 view 上
            if let window = UIApplication.shared.keyWindowCompat {
                passwordSheet.show(in: window)
            } else if let tabBarController = self.tabBarController {
                passwordSheet.show(in: tabBarController.view)
            } else {
                passwordSheet.show(in: view)
            }
        } else {
            // PDF未锁定，直接打开分割页面
            openSplitPDFVC(fileModel: fileModel)
        }
    }
    
    private func openSplitPDFVC(fileModel: DR_FileModel) {
        let pdfModel = DR_PDFFileModel(
            fileName: fileModel.fileName,
            fileURL: fileModel.fileURL,
            fileSize: fileModel.fileSize,
            createDate: fileModel.createDate,
            pageCount: fileModel.pageCount
        )
        let splitVC = DR_SplitPDFVC(pdfFileURL: pdfModel.fileURL)
        pushHidingTabBar(splitVC, animated: true)
    }
    
    // MARK: - 处理收藏切换
    private func handleToggleFavorite(_ fileModel: DR_FileModel) {
        let isNowFavorite = DR_FileManager.shared.toggleFavorite(fileModel)
        if !isNowFavorite {
            // 取消收藏后，从列表中移除
            loadFavoriteFiles()
            view.makeToast("collect_error".localized, duration: 2.0, position: .center)
        } else {
            view.makeToast("collect_succ".localized, duration: 2.0, position: .center)
        }
    }
    
    // MARK: - 处理分享文件
    private func handleShareFile(_ fileModel: DR_FileModel) {
        let activityVC = UIActivityViewController(activityItems: [fileModel.fileURL], applicationActivities: nil)
        
        // 适配iPad
        if let popover = activityVC.popoverPresentationController {
            popover.sourceView = view
            popover.sourceRect = CGRect(x: view.bounds.midX, y: view.bounds.midY, width: 0, height: 0)
            popover.permittedArrowDirections = []
        }
        
        present(activityVC, animated: true)
    }
    
    // MARK: - 处理重命名文件
    private func handleRenameFile(_ fileModel: DR_FileModel) {
        let renameSheet = DR_RenameSheet()
        renameSheet.configure(with: fileModel.displayName)
        
        renameSheet.onConfirm = { [weak self] newName in
            guard let self = self else { return }
            if fileModel.fileType == .pdf {
                // PDF文件使用PDFTool重命名
                if DR_PDFTool.shared.renamePDF(oldFileURL: fileModel.fileURL, newName: newName) != nil {
                    self.view.makeToast("重命名成功", duration: 2.0, position: .center)
                    // 发送文件导入通知，刷新文件列表
                    NotificationCenter.default.post(name: NSNotification.Name("FileImported"), object: nil)
                    self.loadFavoriteFiles()
                } else {
                    self.view.makeToast("重命名失败", duration: 2.0, position: .center)
                }
            } else {
                // 其他文件类型使用通用重命名
                if self.renameFile(oldFileURL: fileModel.fileURL, newName: newName) != nil {
                    self.view.makeToast("重命名成功", duration: 2.0, position: .center)
                    // 发送文件导入通知，刷新文件列表
                    NotificationCenter.default.post(name: NSNotification.Name("FileImported"), object: nil)
                    self.loadFavoriteFiles()
                } else {
                    self.view.makeToast("重命名失败", duration: 2.0, position: .center)
                }
            }
        }
        
        renameSheet.onCancel = {
            // 取消操作，不需要处理
        }
        
        // 确保显示在 window 或 tabBarController 的 view 上
        if let window = UIApplication.shared.keyWindowCompat {
            renameSheet.show(in: window)
        } else if let tabBarController = self.tabBarController {
            renameSheet.show(in: tabBarController.view)
        } else {
            renameSheet.show(in: view)
        }
    }
    
    // MARK: - 重命名文件（通用）
    private func renameFile(oldFileURL: URL, newName: String) -> URL? {
        let fileExtension = oldFileURL.pathExtension
        let sanitizedName = sanitizeFileName(newName)
        let newURL = oldFileURL.deletingLastPathComponent().appendingPathComponent("\(sanitizedName).\(fileExtension)")
        
        // 检查新文件名是否已存在
        if FileManager.default.fileExists(atPath: newURL.path) {
            return nil
        }
        
        // 重命名文件
        do {
            try FileManager.default.moveItem(at: oldFileURL, to: newURL)
            return newURL
        } catch {
            print("❌ [DR_FavoriteVC] 文件重命名失败: \(error.localizedDescription)")
            return nil
        }
    }
    
    // MARK: - 清理文件名
    private func sanitizeFileName(_ fileName: String) -> String {
        let invalidChars = CharacterSet(charactersIn: "/\\?%*|\"<>")
        return fileName.components(separatedBy: invalidChars).joined(separator: "_")
    }
    
    // MARK: - 处理显示详情
    private func handleShowDetails(_ fileModel: DR_FileModel) {
        let detailsSheet = DR_FileDetailsSheet()
        detailsSheet.configure(with: fileModel)
        
        // 确保显示在 window 或 tabBarController 的 view 上
        if let window = UIApplication.shared.keyWindowCompat {
            detailsSheet.show(in: window)
        } else if let tabBarController = self.tabBarController {
            detailsSheet.show(in: tabBarController.view)
        } else {
            detailsSheet.show(in: view)
        }
    }
    
    // MARK: - 处理锁定PDF
    private func handleLockPDF(_ fileModel: DR_FileModel) {
        if DR_PDFTool.shared.hasPassword(for: fileModel.fileURL) {
            // 已设置密码，先验证密码再解锁
            let passwordSheet = DR_EnterPasswordSheet()
            passwordSheet.configure(fileName: fileModel.fileName, fileSize: fileModel.fileSizeString)
            
            passwordSheet.onConfirm = { [weak self, weak passwordSheet] password in
                guard let self = self, let sheet = passwordSheet else { return }
                if DR_PDFTool.shared.verifyPassword(for: fileModel.fileURL, password: password) {
                    if DR_PDFTool.shared.removePassword(for: fileModel.fileURL) {
                        sheet.hide()
                        self.view.makeToast("密码已移除", duration: 2.0, position: .center)
                    } else {
                        self.view.makeToast("移除密码失败", duration: 2.0, position: .center)
                    }
                } else {
                    self.view.makeToast("密码错误", duration: 2.0, position: .center)
                }
            }
            
            passwordSheet.onCancel = {
                // 取消操作，不需要处理
            }
            
            // 确保显示在 window 或 tabBarController 的 view 上
            if let window = UIApplication.shared.keyWindowCompat {
                passwordSheet.show(in: window)
            } else if let tabBarController = self.tabBarController {
                passwordSheet.show(in: tabBarController.view)
            } else {
                passwordSheet.show(in: view)
            }
        } else {
            // 未设置密码，显示设置密码弹窗
            let passwordSheet = DR_SetPasswordSheet()
            
            passwordSheet.onConfirm = { [weak self] password in
                guard let self = self else { return }
                if DR_PDFTool.shared.setPassword(for: fileModel.fileURL, password: password) {
                    self.view.makeToast("密码设置成功", duration: 2.0, position: .center)
                } else {
                    self.view.makeToast("密码设置失败", duration: 2.0, position: .center)
                }
            }
            
            passwordSheet.onCancel = {
                // 取消操作，不需要处理
            }
            
            // 确保显示在 window 或 tabBarController 的 view 上
            if let window = UIApplication.shared.keyWindowCompat {
                passwordSheet.show(in: window)
            } else if let tabBarController = self.tabBarController {
                passwordSheet.show(in: tabBarController.view)
            } else {
                passwordSheet.show(in: view)
            }
        }
    }
    
    // MARK: - 处理删除文件
    private func handleDeleteFile(_ fileModel: DR_FileModel) {
        let deleteSheet = DR_DeleteConfirmSheet()
        
        deleteSheet.onDelete = { [weak self] in
            guard let self = self else { return }
            do {
                try FileManager.default.removeItem(at: fileModel.fileURL)
                // 从收藏中移除
                DR_FileManager.shared.removeFavorite(fileModel)
                // 发送文件导入通知，刷新文件列表
                NotificationCenter.default.post(name: NSNotification.Name("FileImported"), object: nil)
                self.loadFavoriteFiles()
                self.view.makeToast("删除成功", duration: 2.0, position: .center)
            } catch {
                self.view.makeToast("删除失败", duration: 2.0, position: .center)
            }
        }
        
        deleteSheet.onCancel = {
            // 取消操作，不需要处理
        }
        
        // 确保显示在 window 或 tabBarController 的 view 上
        if let window = UIApplication.shared.keyWindowCompat {
            deleteSheet.show(in: window)
        } else if let tabBarController = self.tabBarController {
            deleteSheet.show(in: tabBarController.view)
        } else {
            deleteSheet.show(in: view)
        }
    }
    
    //MARK: action
    @objc private func clickBackButton() {
        self.navigationController?.popViewController(animated: true)
    }
    
    private let backButton: UIButton = {
        let v = UIButton(type: .custom)
        v.setImage("common_back".toImage, for: .normal)
        return v
    }()
    private let titleLabel: UILabel = {
        let v = UILabel()
        v.text = "favorite_title".localized
        v.textAlignment = .center
        v.textColor = .black
        v.font = UIFont.systemFont(ofSize: 18, weight: .bold)
        return v
    }()
}

// MARK: - UICollectionViewDataSource, UICollectionViewDelegate
extension DR_FavoriteVC: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return favoriteFiles.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DR_HomeFileCell.identifier, for: indexPath) as! DR_HomeFileCell
        let fileModel = favoriteFiles[indexPath.item]
        let isFavorite = DR_FileManager.shared.isFavorite(fileModel)
        
        // 隐藏 typeImage
        cell.configure(with: fileModel, isFavorite: isFavorite, hideTypeImage: true)
        
        cell.onFavoriteTapped = { [weak self] in
            guard let self = self else { return }
            let isNowFavorite = DR_FileManager.shared.toggleFavorite(fileModel)
            // 如果取消收藏，从列表中移除
            if !isNowFavorite {
                self.loadFavoriteFiles()
            } else {
                // 刷新当前 cell
                if let cell = collectionView.cellForItem(at: indexPath) as? DR_HomeFileCell {
                    cell.configure(with: fileModel, isFavorite: isNowFavorite, hideTypeImage: true)
                }
            }
        }
        
        cell.onMoreTapped = { [weak self] in
            self?.showMoreActionSheet(for: fileModel)
        }
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let fileModel = favoriteFiles[indexPath.item]
        
        if fileModel.fileType == .pdf {
            // PDF文件需要检查密码
            if DR_PDFTool.shared.hasPassword(for: fileModel.fileURL) {
                // PDF已锁定，需要先输入密码
                let passwordSheet = DR_EnterPasswordSheet()
                passwordSheet.configure(fileName: fileModel.fileName, fileSize: fileModel.fileSizeString)
                
                passwordSheet.onConfirm = { [weak self, weak passwordSheet] password in
                    guard let self = self, let sheet = passwordSheet else { return }
                    if DR_PDFTool.shared.verifyPassword(for: fileModel.fileURL, password: password) {
                        sheet.hide()
                        self.openPDFPreview(fileModel: fileModel, isPasswordVerified: true)
                    } else {
                        self.view.makeToast("密码错误", duration: 2.0, position: .center)
                    }
                }
                
                passwordSheet.onCancel = {
                    // 取消操作，不需要处理
                }
                
                // 确保显示在 window 或 tabBarController 的 view 上
                if let window = UIApplication.shared.keyWindowCompat {
                    passwordSheet.show(in: window)
                } else if let tabBarController = self.tabBarController {
                    passwordSheet.show(in: tabBarController.view)
                } else {
                    passwordSheet.show(in: view)
                }
            } else {
                // PDF未锁定，直接打开预览
                openPDFPreview(fileModel: fileModel)
            }
        } else {
            // 其他文件类型，打开预览
            let previewVC = DR_LookFileVC()
            previewVC.configure(with: fileModel)
            pushHidingTabBar(previewVC, animated: true)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let w = (w_screen - 30 - 24)/3
        return CGSize(width: w, height: 210)
    }
    
    // MARK: - 打开PDF预览
    private func openPDFPreview(fileModel: DR_FileModel, isPasswordVerified: Bool = false) {
        let pdfModel = DR_PDFFileModel(
            fileName: fileModel.fileName,
            fileURL: fileModel.fileURL,
            fileSize: fileModel.fileSize,
            createDate: fileModel.createDate,
            pageCount: fileModel.pageCount
        )
        let previewVC = DR_LookPDFVC()
        previewVC.configure(with: pdfModel, isPasswordVerified: isPasswordVerified)
        pushHidingTabBar(previewVC, animated: true)
    }
}
